<?php
require_once ('config.inc.php');
require_once ('utils.inc.php');
$imgid = $_GET ["imgid"];
if (empty ( $imgid )) {
	header ( "Content-type: text/html; charset=utf-8" );
	die ( 'Not Accepted.' );
}
$con = mysql_connect ( MySQLHost, MySQLUser, MySQLPass );
$imgid = mysql_real_escape_string ( decodeID ( $imgid ) );
if (! $con) {
	header ( $_SERVER ['SERVER_PROTOCOL'] . " 503 Service Temporarily Unavailable", true, 503 );
	showErrorImage ( 503 );
	die ();
}

mysql_select_db ( MySQLDB, $con );

$sql = 'SELECT `ext` ,  `uploaddate`  FROM `imglist` WHERE `imgid` = ' . $imgid;
$result = mysql_query ( $sql );
if (! $result) {
	header ( $_SERVER ['SERVER_PROTOCOL'] . " 500 Internal Server Error", true, 500 );
	showErrorImage ( 500 );
	mysql_close ( $con );
	die ();
}

$row = mysql_fetch_array ( $result );
if (empty ( $row )) {
	header ( $_SERVER ['SERVER_PROTOCOL'] . " 404 Not Found", true, 404 );
	showErrorImage ( 404 );
	mysql_close ( $con );
	die ();
}

$image_time = strtotime ( $row ['uploaddate'] );
if (array_key_exists ( "HTTP_IF_MODIFIED_SINCE", $_SERVER )) {
	$if_modified_since = strtotime ( preg_replace ( '/;.*$/', '', $_SERVER ["HTTP_IF_MODIFIED_SINCE"] ) );
	if ($if_modified_since >= $image_time) {
		header ( $_SERVER ['SERVER_PROTOCOL'] . " 304 Not Modified", true, 304 );
		mysql_close ( $con );
		die ();
	}
}

$sql = 'UPDATE `imglist` SET `clicks` = `clicks`+1 , `lastdate`=now() WHERE
  `imgid` =' . $imgid;
if (! mysql_query ( $sql )) {
	header ( $_SERVER ['SERVER_PROTOCOL'] . " 500 Internal Server Error", true, 500 );
	showErrorImage ( 500 );
	mysql_close ( $con );
	die ();
}

$storename = "upload/" . $_GET ["imgid"] . ".bin";
if (! file_exists ( $storename )) {
	header ( $_SERVER ['SERVER_PROTOCOL'] . " 404 Not Found", true, 404 );
	showErrorImage ( 404 );
	$sql = 'DELETE FROM `imglist` WHERE `imgid` =' . $imgid;
	@mysql_query ( $sql );
	mysql_close ( $con );
	die ();
}
$file = fopen ( $storename, "r" ); // 打开文件
$ct = file_ct ( $row ['ext'] );
Header ( 'Content-type: ' . $ct );
Header ( "Accept-Ranges: bytes" );
Header ( "Accept-Length: " . filesize ( $storename ) );
header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s', $image_time ) . ' GMT', true, 200 );
header ( 'Expires: ' . gmdate ( 'D, d M Y H:i:s', $image_time + 86400 * 365 ) . ' GMT', true, 200 );
header ( "Pragma: public" );
header ( "Cache-Control: maxage=" . (86400 * 14) );
echo fread ( $file, filesize ( $storename ) );
fclose ( $file );
mysql_close ( $con );
?>

